# -*- coding:utf-8 -*-
from datetime import datetime, timedelta

from django.core.cache import cache
from django.db.migrations import serializer
from django.shortcuts import render
from django.views import View
from rest_framework.views import APIView
from rest_framework.response import Response
from django.http import HttpResponse, JsonResponse, response
from Apps.common.response import SuccessResponse

from ..models.demo import Demo
import json
from rest_framework.viewsets import ModelViewSet
from ..ser.demoser import demoSer
from Apps.common.send_email import send

from ..tasks import add

from django.template import Context, Template

# from channels.layers import get_channel_layer
# from asgiref.sync import async_to_sync
#
# channel_layer = get_channel_layer()
#
# def send_msg():
#     async_to_sync(channel_layer.group_send)("a965b28b-d282-4178-842c-78feb14bab06", {"type": "getMenu",
#                                                                                      "text": '{"name": "1234"}'})


# 函数方式
from ...common.testTem.base import Tem


def demo_view(request):
    # 发邮件
    # send(request.META["REMOTE_ADDR"], request.META)

    # cache.set("demo", request.META)
    # send_msg()

    template = "Hello {{ name  }}!"
    context = {'name': "demo"}

    result_te = Tem(template, context).result

    return HttpResponse(result_te)


# 自带视图
class api_view(View):
    def get(self, request, *args, **kwargs):
        result = add.delay(12, 23)
        print(result)
        return HttpResponse(f"'请求参数解析：'{request.META}")


# drf APIView 继承 View
class re_api_view(APIView):
    authentication_classes = []

    def get(self, request, *args, **kwargs):
        result = Demo.objects.all().values("name", "age")
        # DecimalField,DateTimeField 格式问题，不能直接成json,需要自己组装json
        # 'money': Decimal('34.4500'), 'create_time': datetime.datetime(2022, 5, 2, 22, 39, 38)
        demo_list = list(result)
        return JsonResponse(demo_list, safe=False, json_dumps_params={"ensure_ascii": False})


# 自带的serializer序列化(没实现，大概就是这样）
class ser_api_view(View):
    def get(self, request, *args, **kwargs):
        result = Demo.objects.all().values("name", "age")
        rep = serializer.BaseSerializer(result)
        return HttpResponse(rep.value)


class Base_View(ModelViewSet):
    serializer_class = demoSer
    queryset = Demo.objects.all()
    authentication_classes = []


class celery_view(View):
    def get(self, request, *args, **kwargs):
        ctime = datetime.now()
        print(ctime)
        # 默认用utc时间
        utc_ctime = datetime.utcfromtimestamp(ctime.timestamp())
        print(utc_ctime)
        time_delay = timedelta(seconds=10)
        task_time = utc_ctime + time_delay
        print(task_time)
        result = add.apply_async((26, 45), eta=task_time)
        print(result.id)

        return HttpResponse(f"'任务执行ID：'{result}")


from celery import result


def get_result_by_taskid(request):
    task_id = request.GET.get('task_id')
    print(task_id)
    # 异步执行
    ar = result.AsyncResult(task_id)

    if ar.ready():
        return JsonResponse({'status': ar.state, 'result': ar.get()})
    else:
        return JsonResponse({'status': ar.state, 'result': ''})


################################# 异步任务

# 1. 声明一个和celery一模一样的任务函数，但是我们可以导包来解决

# send_sms.delay("110")
# send_sms2.delay("119")
# send_sms.delay() 如果调用的任务函数没有参数，则不需要填写任何内容


################################# 定时任务

# ctime = datetime.now()
# # 默认用utc时间
# utc_ctime = datetime.utcfromtimestamp(ctime.timestamp())
# time_delay = timedelta(seconds=10)
# task_time = utc_ctime + time_delay
# result = send_sms.apply_async(["911", ], eta=task_time)
# print(result.id)


################################聊天系统
import logging
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync

channel_layer = get_channel_layer()

logger = logging.getLogger("django")
# LoginMsg
from Apps.common.chart_request.e_chart import Chart


def send_sk_msg(user_id, text):
    async_to_sync(channel_layer.group_send)(user_id, {"type": "sendMsg", "text": text})


class send_sk_msg_view(APIView):
    def post(self, request, *args, **kwargs):
        # Chart().sendText()
        # Chart().getSimpleList()
        send_sk_msg(request.user.id, request.data["data"])

        logger.info(f"发送的用户:{request.user.id}")
        logger.info(f"发送的消息:{request.data['data']}")
        logger.info(f"sk测试消息已成功发送:{self.__class__.__name__}")

        return HttpResponse("success")
